/**
 * Copyright (C) Study Information Technology, LTD. 
 * All Rights Reserved.
 *
 * ApplicationStartup.java created on 2020年3月5日 下午7:50:54 by Lyon Lu 
 */
package com.mvc.server.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.mvc.server.datasource.pojo.Ds;
import com.mvc.server.datasource.service.DatasourceService;

/**
 * <pre>
 * Description:
 * 	容器启动成功后执行， 可初始化数据、注入bean等
 * 
 * 	注入bean需要DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
 * @author Lyon Lu
 * @date 2020年3月5日 下午7:50:54
 *
 * </pre>
 */
@Component
public class ApplicationStartup implements CommandLineRunner{

	@Resource
	private ApplicationContext applicationContext;
	
	@Override
	public void run(String... args) throws Exception {
		
		DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext
				.getAutowireCapableBeanFactory();

		// 获取容器中所有数据源
		Map<String, DataSource> dataSourceBeanMap = applicationContext.getBeansOfType(DataSource.class);
		Map<Object, Object> dataSourceMap = new HashMap<>();
		for (Entry<String, DataSource> entry : dataSourceBeanMap.entrySet()) {
			if (!(entry.getValue() instanceof AbstractRoutingDataSource)) {
				dataSourceMap.put(entry.getKey(), entry.getValue());
			}
		}

		DatasourceService datasourceService = applicationContext.getBean(DatasourceService.class);
		List<Ds> allDs = datasourceService.findAllDs();
		if (CollectionUtils.isNotEmpty(allDs)) {
			for (Ds ds : allDs) {
				DruidDataSource builder = DruidDataSourceBuilder.create().build();
				builder.setUrl(ds.getUrl());
						
				builder.setUsername(ds.getUserName());
				builder.setPassword(ds.getPassword());
				builder.setDriverClassName(ds.getDriverClassName());
				beanFactory.registerSingleton(ds.getDataSourceId(), builder);
				dataSourceMap.put(ds.getDataSourceId(), builder);
			}
		}
		
		AbstractRoutingDataSource dataSource = applicationContext.getBean(AbstractRoutingDataSource.class);
		dataSource.setTargetDataSources(dataSourceMap);
		dataSource.afterPropertiesSet();
	}
}
